# -*- coding: utf-8 -*-

"""
DateTime   : 2021/02/16 10:21
Author     : ZhangYafei
Description: 
"""
import os
import re

import requests


def main():
    url = "https://www.qiushibaike.com/imgrank/page/{}/"
    ua_headers = {"User-Agent": 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)'}
    # 指定其实页码和结束页码
    page_start = int(input('请输入开始页面:'))
    page_end = int(input('请输入结束页面:'))
    # 找文件夹，如果没有则创建一个
    if not os.path.exists('Images'):
        os.mkdir('Images')
    # 循环下载
    for page in range(page_start, page_end + 1):
        print('正在下载第%d页图片...' % page)
        new_url = url.format(page)
        print(new_url)
        responses = requests.get(url=new_url, headers=ua_headers)
        if responses.status_code == 200:
            res = responses.text
        else:
            print('页面没有响应')
            continue
        pattern = re.compile('''<div class="thumb">.*?<img src="(.*?)".*?>.*?</div>''', re.S)
        items = re.findall(pattern, res)
        for item in items:
            url_image = 'https:' + item
            name_image = item.split('/')[-1]
            image_path = 'Images/' + name_image
            image_data = requests.get(url=url_image, headers=ua_headers).content
            with open(image_path, 'wb') as f:
                f.write(image_data)


if __name__ == '__main__':
    main()
